/**
 * 
 * @param {*} lists 需要打印的数组
 * @param {*} printerNum 打印机对应编号
 * @param {*} type 打印 true/预览 false
 */

import { getLodop ,needCLodop} from '@/utils/LodopFuncs.js'
import { parseTime } from '@/utils/ruoyi'
import { getPrinterByIpAndPrinterType } from "@/api/system/printer";
import { genCirculationRegister, genDosageNotification } from "@/api/slides/task";
import { blobToBase64 } from "@/utils/file";
import { listByIds } from "@/api/system/oss";
import { MessageBox } from 'element-ui';

export async function printCode(lists, printerNum, type = false) {
  const printList = [...lists]
  if(needCLodop()) {
    try {
      let LODOP = getLodop();

      // 查询打印机
      await getPrinterByIpAndPrinterType(printerNum).then((responsePrinter) => {
        LODOP.SET_PRINT_MODE('WINDOW_DEFPRINTER', responsePrinter.rows[0].printerName)
        LODOP.SET_PRINTER_INDEXA(responsePrinter.rows[0].printerName);
      }).catch(err => {});
      
      LODOP.PRINT_INIT('条码编号')

      console.log("---------", LODOP.GET_PRINTER_NAME(0));
      console.log("---------", LODOP.GET_PRINTER_NAME(1));
      console.log("---------", LODOP.GET_PRINTER_COUNT());
      console.log("---------PaperLength", LODOP.GET_PRINTER_NAME("0:PaperLength"));
      console.log("---------PaperWidth", LODOP.GET_PRINTER_NAME("0:PaperWidth"));
      console.log("---------MaxExtentWidth", LODOP.GET_PRINTER_NAME("0:MaxExtentWidth"));
      console.log("---------PaperSize", LODOP.GET_PRINTER_NAME("0:PaperSize"));
      console.log("---------PortName", LODOP.GET_PRINTER_NAME("0:PortName"));
      console.log("---------MinExtentWidth", LODOP.GET_PRINTER_NAME("0:MinExtentWidth"));
      console.log("---------Copies", LODOP.GET_PRINTER_NAME("0:Copies"));
      // console.log("---------", LODOP.GET_PRINTER_NAME("1:MaxExtentWidth"));

        let num = Math.ceil(printList.length / 2)
        LODOP.SET_PRINT_PAGESIZE(1, `7.8cm`, `${16}mm`,"");
        LODOP.SET_PRINT_MODE('POS_BASEON_PAPER', true)
        printList.forEach((item, index) => {
          console.log(item);
          
          // 设置每两条数据创建纸张
          let xStandard = index % 2 == 0 ? 0 : 40 // 纸张x轴
          let yMultiple = Math.ceil((index + 1) / 2) // 行数倍率
          let yStandard = 0 // y轴偏移量
          // let yStandard = (yMultiple - 1) * 20 // y轴偏移量

          let offset = xStandard; /* 水平便宜量 */
          let offsetOri = yStandard; /* 垂直偏移量 */
          // 委托单位------------------------------------
          // item.entrustOrganizationName = '贵州省贵阳市贵州省贵阳市贵州省贵阳市'
          item.entrustOrganizationName = item.entrustOrganizationName?.length > 14 ? 
                                          (item.entrustOrganizationName.slice(0, 13) + '...') : 
                                          item.entrustOrganizationName
          LODOP.ADD_PRINT_TEXT(`${0 + offsetOri}mm`, `${2 + offset}mm`, "100%", "100%", item.entrustOrganizationName || "");
          // LODOP.SET_PRINT_STYLEA(0, "FontSize", );
          LODOP.SET_PRINT_STYLEA(0, "FontSize", 7);
          LODOP.SET_PRINT_STYLEA(0, "Bold" , 1);
          // // 部门-------------------------------------
          // LODOP.ADD_PRINT_TEXT(`${6 + offsetOri}mm`, `${2 + offset}mm`,"100%","100%", item.entrustDeptName || "");
          // LODOP.SET_PRINT_STYLEA(0, "FontSize", 8);
          // LODOP.SET_PRINT_STYLEA(0, "Bold" , 1);
          // // 铅衣--------------------------------------
          // if(item.personnelName == "环境对照") {
          // 	LODOP.ADD_PRINT_TEXT(`${11 + offsetOri}mm`, `${2 + offset}mm`,"100%","100%", "");
          // }else {
          // 	LODOP.ADD_PRINT_TEXT(`${11 + offsetOri}mm`, `${2 + offset}mm`, "100%","100%",
          // 		`${item.dosageType == "1" ? '铅衣内' :
          // 		item.dosageType == "2" ? '铅衣外' :
          // 		item.dosageType == "3" ? '本底' : ''}`);
          // }
          // LODOP.SET_PRINT_STYLEA(0, "FontSize", 8);
          // LODOP.SET_PRINT_STYLEA(0, "Bold" , 1);
          // 二维码---------------------------------------------
          const dosageIndex = item.dosageNumber.indexOf('-')
          const dosageNumberArr = item.dosageNumber.split('')
          dosageNumberArr.splice(dosageIndex, 0, `-${item.batchNum}`)
          let dosNumber = dosageNumberArr.join('')
          
          LODOP.ADD_PRINT_BARCODE(`${3.2 + offsetOri}mm`, `${26 + offset}mm`, "16mm", "16mm", "QRCode", dosNumber);
          LODOP.SET_PRINT_STYLEA(0,"QRCodeVersion",5);
          LODOP.SET_PRINT_STYLEA(0,"DataCharset",'UTF-8');
          LODOP.SET_PRINT_STYLEA(0, "FontSize", 8);

          // 条码号------------------------------------
          dosageNumberArr.splice(dosageIndex, 0, `${item.year}`)
          let dosNumbers = dosageNumberArr.join('')
          LODOP.ADD_PRINT_TEXT(`${8 + offsetOri}mm`, `${2 + offset}mm`,"100%","100%", `${dosNumbers || ''}`);
          LODOP.SET_PRINT_STYLEA(0, "FontSize", 6);
          LODOP.SET_PRINT_STYLEA(0, "Bold" , 1);

          // 姓名------------------------------------
          LODOP.ADD_PRINT_TEXT(`${4 + offsetOri}mm`, `${2 + offset}mm`,"100%","100%", `${item.personnelName || ''}` + `${item.dosageType == "1" ? '(内)' :
                                                                                                                           item.dosageType == "2" ? '(外)' : ''}`);
          LODOP.SET_PRINT_STYLEA(0, "FontSize", 8);
          LODOP.SET_PRINT_STYLEA(0, "Bold" , 1);

          // 科室------------------------------------
          LODOP.ADD_PRINT_TEXT(`${8 + offsetOri}mm`, `${2 + offset}mm`,"100%","100%", `${item.entrustDeptName || ''}`);
          LODOP.SET_PRINT_STYLEA(0, "FontSize", 8);
          LODOP.SET_PRINT_STYLEA(0, "Bold" , 1);

          // 时间------------------------------------
          LODOP.ADD_PRINT_TEXT(`${12 + offsetOri}mm`, `${2 + offset}mm`,"100%","100%", `${parseTime(item.wearingBeginTime, "{y}/{m}/{d}")}-${parseTime(item.wearingEndTime, "{y}/{m}/{d}")}`);
          LODOP.SET_PRINT_STYLEA(0, "FontSize", 6);
          LODOP.SET_PRINT_STYLEA(0, "Bold" , 1);
          if (index % 2 == 1) {
            LODOP.NEWPAGE();
          }
        });
      if (type) {
        LODOP.PRINT();
      } else {
        LODOP.PREVIEW();
      }
    } catch (error) {
      console.log("error", error);
      MessageBox.alert(`检测到您还未安装C-LODOP套打控件,请确认启用后再打印。或您可点击下载该套打控件，安装成功后刷新页面再进行打印`, '提示', {
        confirmButtonText: '确定',
        callback: action => {
          if (action === 'confirm')
            window.open('https://www.lodop.net/download.html' );
        }
      });
    }
  }
}

export async function printCodeZY(lists, printerNum, type = false) {
  const printList = JSON.parse(JSON.stringify(lists))
  console.log(printList)
  if (!needCLodop()) return
  let LODOP = getLodop()
  if (!LODOP) {
    MessageBox.alert(`检测到您还未安装C-LODOP套打控件,请确认启用后再打印。或您可点击下载该套打控件，安装成功后刷新页面再进行打印`, '提示', {
      confirmButtonText: '确定',
      callback: action => {
        if (action === 'confirm') window.open('https://www.lodop.net/download.html')
      }
    })
  }
  // 查询打印机
  const res = await getPrinterByIpAndPrinterType(printerNum).catch(err => {})
  if (!res) return

  LODOP.SET_PRINT_MODE('WINDOW_DEFPRINTER', res.rows[0].printerName)
  LODOP.SET_PRINTER_INDEXA(res.rows[0].printerName)
  LODOP.PRINT_INITA(0, 0, `50mm`, `20mm`, '条码编号')

  printList.forEach((item, index) => {
    LODOP.SET_PRINT_PAGESIZE(1, `50mm`, `20mm`, '')
    LODOP.SET_PRINT_MODE('POS_BASEON_PAPER', true)

    // 姓名------------------------------------
    let name = item.personnelName + (item.dosageType == 1 ? '(内)' : item.dosageType == 2 ? '(外)' : '')
    LODOP.ADD_PRINT_TEXT(`3mm`, `5mm`, '100%', '100%', name)
    LODOP.SET_PRINT_STYLEA(0, 'FontSize', 9)
    LODOP.SET_PRINT_STYLEA(0, 'Bold', 1)

    // 身份证号------------------------------------
    let idCard = item.personnelIdCard
    if (idCard) {
      LODOP.ADD_PRINT_TEXT(`6.5mm`, `4mm`, '100%', '100%', idCard)
      LODOP.SET_PRINT_STYLEA(0, 'FontSize', 6)
      LODOP.SET_PRINT_STYLEA(0, 'Bold', 1)
    }

    // 一维码---------------------------------------------
    // const dosageNumberArr = item.dosageNumber.split('')
    // const dosageIndex = item.dosageNumber.indexOf('-')
    // dosageNumberArr.splice(dosageIndex, 0, `-${item.batchNum}`)
    // let dosNumber = dosageNumberArr.join('')
    LODOP.ADD_PRINT_BARCODE(`8.5mm`, `3mm`, '30mm', '10mm', 'Code93', item.dosageNumber)
    LODOP.SET_PRINT_STYLEA(0, 'FontSize', 5)
    LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 1)
    LODOP.SET_PRINT_STYLEA(0, 'AlignJustify', 2)

    LODOP.NEWPAGE()
  })

  if (type) LODOP.PRINT()
  else LODOP.PREVIEW()
}

// 流转登记表
export async function handlePrintTurnoverRegister(taskPersonalDosimeterId, printerNum, type = false) {
  let LODOP = getLodop()

  // 查询打印机
  await getPrinterByIpAndPrinterType(printerNum).then((responsePrinter) => {
    LODOP.SET_PRINT_MODE('WINDOW_DEFPRINTER', responsePrinter.rows[0].printerName)
    LODOP.SET_PRINTER_INDEXA(responsePrinter.rows[0].printerName);
  });
  
  LODOP.PRINT_INIT('流转登记表')
  LODOP.SET_PRINT_PAGESIZE(1, 0, 0, 'A4')

  genCirculationRegister(taskPersonalDosimeterId).then(response => {
    // console.log(response);
    // listByIds(res.data).then((response) => {
    // 	window.open(response.data[0].url, 'pdf')
    // });
    let binaryData = []
    binaryData.push(response.data)
    blobToBase64(
      new Blob(binaryData, { type: 'application/pdf' })
    ).then((res) => {
      LODOP.ADD_PRINT_PDF(
        '0',
        '0',
        '100%',
        '100%',
        res.split('data:application/pdf;base64,')[1]
      )
      // console.log(res);
      // 设置对后台打印状态进行捕获
      // LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
      if (type) {
        LODOP.PRINT();
      } else {
        LODOP.PREVIEW();
      }
    })
  })
}

// 告知书
export async function handlePrintNotice(taskPersonalDosimeterId, printerNum, type = false) {
  let LODOP = getLodop()

  // 查询打印机
  await getPrinterByIpAndPrinterType(printerNum).then((responsePrinter) => {
    LODOP.SET_PRINT_MODE('WINDOW_DEFPRINTER', responsePrinter.rows[0].printerName)
    LODOP.SET_PRINTER_INDEXA(responsePrinter.rows[0].printerName);
  });
  
  LODOP.PRINT_INIT('告知书')
  LODOP.SET_PRINT_PAGESIZE(1, 0, 0, 'A4')

  genDosageNotification(taskPersonalDosimeterId).then(response => {
    // console.log(response);
    // listByIds(res.data).then((response) => {
    // 	window.open(response.data[0].url, 'pdf')
    // });
    let binaryData = []
    binaryData.push(response.data)
    blobToBase64(
      new Blob(binaryData, { type: 'application/pdf' })
    ).then((res) => {
      LODOP.ADD_PRINT_PDF(
        '0',
        '0',
        '100%',
        '100%',
        res.split('data:application/pdf;base64,')[1]
      )
      // console.log(res);
      // 设置对后台打印状态进行捕获
      // LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
      if (type) {
        LODOP.PRINT();
      } else {
        LODOP.PREVIEW();
      }
    })
  })
}

// 报告批量打印
export async function handlePrintReport(ossIds, printerNum, type = false) {
  let LODOP = getLodop()

  // 查询打印机
  await getPrinterByIpAndPrinterType(printerNum).then((responsePrinter) => {
    LODOP.SET_PRINT_MODE('WINDOW_DEFPRINTER', responsePrinter.rows[0].printerName)
    LODOP.SET_PRINTER_INDEXA(responsePrinter.rows[0].printerName);
  });
  
  LODOP.PRINT_INIT('报告')
  LODOP.SET_PRINT_PAGESIZE(1, 0, 0, 'A4')

  ossIds.map(async item => {
    if (!item.ossId) return;
    let {data} = await listByIds(item.ossId)
    LODOP.ADD_PRINT_PDF(
      '0',
      '0',
      '100%',
      '100%',
      data[0].url
    )
    // console.log(res);
    // 设置对后台打印状态进行捕获
    // LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
    if (type) {
      LODOP.PRINT();
    } else {
      LODOP.PREVIEW();
    }
    // 打印
    // let binaryData = []
    // binaryData.push(response.data)
    // blobToBase64(
    //   new Blob(binaryData, { type: 'application/pdf' })
    // ).then((res) => {
    //   LODOP.ADD_PRINT_PDF(
    //     '0',
    //     '0',
    //     '100%',
    //     '100%',
    //     res.split('data:application/pdf;base64,')[1]
    //   )
    //   // console.log(res);
    //   // 设置对后台打印状态进行捕获
    //   // LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
    //   if (type) {
    //     LODOP.PRINT();
    //   } else {
    //     LODOP.PREVIEW();
    //   }
    // })

  })
}

// 打印任务计划书
export async function handlePrintTaskPlan(planOssId, printerNum, type = false) {
  let LODOP = getLodop()

  // 查询打印机
  await getPrinterByIpAndPrinterType(printerNum).then(res => {
    LODOP.SET_PRINT_MODE('WINDOW_DEFPRINTER', res.rows[0].printerName)
    LODOP.SET_PRINTER_INDEXA(res.rows[0].printerName)
  })
  
  LODOP.PRINT_INIT('任务计划')
  LODOP.SET_PRINT_PAGESIZE(1, 0, 0, 'A4')

  // genDosageNotification(planOssId).then(response => {
  //   let binaryData = []
  //   binaryData.push(response.data)
  //   blobToBase64(new Blob(binaryData, { type: 'application/pdf' }) ).then((res) => {
  //     LODOP.ADD_PRINT_PDF('0', '0', '100%', '100%', res.split('data:application/pdf;base64,')[1])
  //     type ? LODOP.PRINT() : LODOP.PREVIEW()
  //   })
  // })
}